package com.xframe.xdal.core.model.sqlbuilder;

import com.xframe.xdal.core.domain.XDynamicModel;
import com.xframe.xdal.core.util.XReflect;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.ClassUtils;

import java.util.Collection;

/**
 * 功能描述: 数据处理wrap
 *
 * @author xufeng
 * @version 1.0
 * @date 2022-09-26
 */
@Data
public class DataWrap {

    /**
     * 数据集
     */
    @Setter(AccessLevel.NONE)
    @Getter(AccessLevel.NONE)
    private Object data;


    //private Collection<E> collection;

    /**
     * 数据类型
     */
    @Setter(AccessLevel.NONE)
    private Class<?> dataType;

    /**
     * 是否有多行数据
     */
    @Setter(AccessLevel.NONE)
    private boolean isManyLineData;

    private DataWrap() {
    }


    /**
     * 创建datawarp 对象
     *
     * @param entity     对象
     * @param entityType 对象类型
     * @return DataWrap
     */
    public static DataWrap crateDataWrap(Object entity, Class<?> entityType) {
        DataWrap dataWrap = new DataWrap();
        dataWrap.data = entity;
        dataWrap.isManyLineData = false;
        dataWrap.dataType = entityType;
        return dataWrap;
    }

    /**
     * 创建datawarp 对象
     *
     * @param collection     对象
     * @param dataType 对象类型
     * @return DataWrap
     */
    public static DataWrap crateDataWrap(Collection collection, Class<?> dataType) {
        DataWrap dataWrap = new DataWrap();
        dataWrap.data = collection;
        dataWrap.isManyLineData = true;
        dataWrap.dataType = dataType;
        return dataWrap;
    }


    /**
     * 创建datawarp 对象
     *
     * @param entity     对象
     *
     * @return DataWrap
     */
    public static DataWrap crateDataWrap(Object entity) {
        return crateDataWrap(entity,entity.getClass());
    }


    public Object getObjectFieldValue(String name){
        if(this.data instanceof XDynamicModel){
            return ((XDynamicModel)this.data).get(name);
        }
        if(this.dataType.isPrimitive() || ClassUtils.isPrimitiveOrWrapper(this.dataType) || this.data instanceof String){
            return this.data;
        }
        return XReflect.getFieldValue(this.data,name);
    }


    public Collection getCollection(){
        return (Collection)this.data;
    }

}
